﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Site.Properties;
using SDT.Site.Areas.User.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;
namespace SDT.Site.Areas.User.Controllers
{
    public class companyController : Controller
    {
        //
        // GET: /User/company/
        /// <summary>
        /// Created by: Vietlv
        /// Created date: 06/07/2011
        /// Description: Manage Articles - Class Article controler;
        /// </summary>

        SDTDataContext eDataContext = new SDTDataContext();

        #region GET: /Article/ Index(int? Page)
        public ActionResult Index(int? page)
        {
            try
            {
                if (page == null) page = 1;
                string order = UserState.getUserStateFromRequest("article.order", "order", "ID").ToString();
                string orderDir = UserState.getUserStateFromRequest("article.orderDir", "orderDir", "desc").ToString();
                int catID = ConfigManager.GetTindoanhnghiep();
                string keyword = UserState.getUserStateFromRequest("article.Keyword", "Keyword", "").ToString();
                keyword = keyword.Trim();
                int pageSize = int.Parse(UserState.getUserStateFromRequest("article.pageSize", "PageSize", 20).ToString());
                var articles = eDataContext.Articles
                    .Where(e => e.CatID == catID)
                    .Where(e => e.AddBy.Equals(UserManager.GetUserId()))
                    .Where(a => (string.IsNullOrEmpty(keyword) ? true :
                        (a.Title.ToLower().Contains(keyword.ToLower()) ||
                        a.Summary.ToLower().Contains(keyword.ToLower()) ||
                        a.ArticleContent.Contains(keyword)
                        )))
                    .OrderBy(string.Format("{0} {1}", order, orderDir))
                    .ToPagedList(page.Value - 1, pageSize);

                ViewData["orderDir"] = orderDir;
                ViewData["order"] = order;

                return View(new CompanyIndexViewModel
                {
                    Articles = articles,
                    Keyword = keyword,
                    ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix
                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Article/Create

        public ActionResult Create()
        {
            var company = eDataContext.Companies.ToList();
            return View(new CompanyEditViewModel()
            {
                Companys = company
            });
        }
        #endregion

        #region POST: /Article/Create
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(CompanyEditViewModel cv)
        {
            try
            {
                // Modified by Vietlv (04/08/2011)
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open(); //Vietlv
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();                                   //Vietlv               
                // TODO: Add insert logic here
                UpdateModel(cv);
                cv.Article.CatID = ConfigManager.GetTindoanhnghiep();
                cv.Article.AddDate = DateTime.Now ;
                cv.Article.AddBy = UserManager.GetUserId();
                eDataContext.Articles.InsertOnSubmit(cv.Article);
                eDataContext.SubmitChanges();
                var companyid = Request["CompanyID"] != string.Empty ? Utils.ParseInt(Request["CompanyID"]) : 0;
                // Insert table ArticleCompanyMap
                if (companyid > 0)
                {
                    var articleCompanyMap = new ArticleCompanyMap();
                    articleCompanyMap.ArticleID = cv.Article.ID;
                    articleCompanyMap.CompanyID = companyid;
                    eDataContext.ArticleCompanyMaps.InsertOnSubmit(articleCompanyMap);
                }
                //Image upload
                HttpPostedFileBase fileImage = Request.Files["ArticleImage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    cv.Article.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}\\{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath), "" + cv.Article.ID);
                }

                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Article/Edit/5
        public ActionResult Edit(int id)
        {
            var currentCompanyid = eDataContext.ArticleCompanyMaps.Where(e => e.ArticleID == id).SingleOrDefault();

            var cp = currentCompanyid == null ? null : eDataContext.Companies.Where(e => e.ID == currentCompanyid.CompanyID).SingleOrDefault();
            
            var article = eDataContext.Articles.Where(a => a.ID == id).SingleOrDefault();

            var company = eDataContext.Companies.ToList();

            return View(new CompanyEditViewModel
            {
                Article = article,
                Companys = company,
                CurrentCompany = cp,
                ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix,
                FileRootURL = Settings.Default.SiteRootUrl + Settings.Default.DocumentInArticlePreviewUrl

            });
        }
        #endregion

        #region POST: /Article/Edit/5
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(int id, CompanyEditViewModel a)
        {
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                // TODO: Add update logic here
                a.Article = eDataContext.Articles.Where(ar => ar.ID == id).SingleOrDefault();
                UpdateModel(a);

                //image upload
                HttpPostedFileBase fileImage = Request.Files["ArticleImage"];
                if (fileImage != null && fileImage.FileName.Length > 0)
                {
                    //Delete old image
                    if (!string.IsNullOrEmpty(a.Article.ImagePath) && System.IO.File.Exists(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath, "" + a.Article.ID + "_" + a.Article.ImagePath)))
                        Uploads.DeleteFile(string.Format("{0}\\{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath, "" + a.Article.ID + "_" + a.Article.ImagePath));

                    //DO upload new image
                    a.Article.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath), "" + a.Article.ID);

                }
                eDataContext.SubmitChanges();

                // Delete old map to articles
                var cp = eDataContext.ArticleCompanyMaps.Where(e => e.ArticleID == id);
                if (cp != null) eDataContext.ArticleCompanyMaps.DeleteAllOnSubmit(cp);
                eDataContext.SubmitChanges();

                // Isert new map to article
                var companyid = Request["CompanyID"] != string.Empty ? Utils.ParseInt(Request["CompanyID"]) : 0;
                // Insert table ArticleCompanyMap
                if (companyid > 0)
                {
                    var articleCompanyMap = new ArticleCompanyMap();
                    articleCompanyMap.ArticleID = a.Article.ID;
                    articleCompanyMap.CompanyID = companyid;
                    eDataContext.ArticleCompanyMaps.InsertOnSubmit(articleCompanyMap);
                }

                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Article/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                var item = eDataContext.Articles.Single(e => e.ID == id);
                return View(item);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Article/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {

                var item = eDataContext.Articles.Single(e => e.ID == id);
                if (item != null)
                {
                    Uploads.DeleteFile(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath, item.ID + "_" + item.ImagePath));
                    // Delete articleCompanyMap
                    var artCompany = eDataContext.ArticleCompanyMaps.Where(e => e.ArticleID == id).ToList();
                    eDataContext.ArticleCompanyMaps.DeleteAllOnSubmit(artCompany);

                    // Delete artcleProjectMap
                    var artProject = eDataContext.ArticleProjectMaps.Where(e => e.ArticleID == id).ToList();
                    eDataContext.ArticleProjectMaps.DeleteAllOnSubmit(artProject);

                    // Delete articleEventMap
                    var artEvent = eDataContext.ArticleEventMaps.Where(e => e.ArticleID == id).ToList();
                    eDataContext.ArticleEventMaps.DeleteAllOnSubmit(artEvent);

                    // Delete articleTagMap
                    var artTag = eDataContext.ArticleTagMaps.Where(e => e.ArticleID == id).ToList();
                    eDataContext.ArticleTagMaps.DeleteAllOnSubmit(artTag);

                    // List Document
                    var listDocument = eDataContext.DocumentsInArticles.Where(e => e.ArticleID == id).Select(e => e.Document).ToList();
                    // Delete file in folder
                    foreach (var currentDocument in listDocument)
                    {
                        var filePath = Settings.Default.SiteRootPath + Settings.Default.DocumentInArticleRootPath + currentDocument.ID + "\\" + currentDocument.Path;
                        Uploads.DeleteFile(filePath);
                    }

                    // Delete Document in article 
                    var documentInArt = eDataContext.DocumentsInArticles.Where(e => e.ArticleID == id).ToList();
                    eDataContext.DocumentsInArticles.DeleteAllOnSubmit(documentInArt);
                    eDataContext.SubmitChanges();

                    // Delete list Document
                    eDataContext.Documents.DeleteAllOnSubmit(listDocument);
                    // Delete current article
                    eDataContext.Articles.DeleteOnSubmit(item);
                    eDataContext.SubmitChanges();
                }
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion
    }
}
